import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../widget/loading_dialog.dart';
import 'async_task_utils.dart';

final AsyncTaskUtils _asyncTaskManager = AsyncTaskUtils();

String? _currentShowToast;

Future<void> toast(
  String message, {
  Alignment? alignment = Alignment.center,
  Color? backgroundColor,
}) async {
  if (_currentShowToast == message) {
    return;
  }
  _currentShowToast = message;
  return SmartDialog.showToast(
    message,
    alignment: alignment,
    maskColor: backgroundColor,
    onDismiss: () {
      _currentShowToast == null;
    },
  );
}

bool _isShowLoadingDialog = false;

Future<void> showLoading({bool isClose = false}) {
  Future<void> show() async {
    if (!_isShowLoadingDialog) {
      Completer<void> completer = Completer();
      _isShowLoadingDialog = true;
      SmartDialog.show(
          builder: (_) {
            if (!completer.isCompleted) {
              Future.delayed(Duration.zero).then((value) {
                completer.complete();
              });
            }
            return const LoadingDialog();
          },
          tag: "loading_dialog_tag",
          maskColor: const Color(0x00FFFFFF),
          clickMaskDismiss: isClose,
          backDismiss: isClose,
          animationType: SmartAnimationType.fade,
          onDismiss: () {
            _isShowLoadingDialog = false;
          });
      return completer.future;
    }
  }

  Completer<void> completer = Completer();
  _asyncTaskManager.syncRun(Task(fun: show, complete: completer));
  return completer.future;
}

Future<void> dismissLoading() {
  Future<void> dismiss() async {
    _isShowLoadingDialog = false;
    await SmartDialog.dismiss(tag: "loading_dialog_tag", force: true);
  }

  Completer<void> completer = Completer();
  _asyncTaskManager.syncRun(Task(fun: dismiss, complete: completer));
  return completer.future;
}
